package cn.bdqn.t354.service.impl;

import cn.bdqn.t354.mapper.RightMapper;
import cn.bdqn.t354.pojo.Right;
import cn.bdqn.t354.service.RightService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class RightServiceImpl implements RightService {
    @Resource
    private RightMapper rightMapper;

    @Override
    public List<Right> findAllRights() {
        return rightMapper.selectList(null);
    }

    @Override
    public List<Right> findRightsByRoleId(Long roleId) {
        return rightMapper.findRightsByRoleId(roleId);
    }

    @Override
    public Map<String,String> loadFilterChainDefinitions(){
        Map<String,String> filterMap=new LinkedHashMap<>();
        filterMap.put("/css/**","anon");
        filterMap.put("/fonts/**","anon");
        filterMap.put("/images/**","anon");
        filterMap.put("/js/**","anon");
        filterMap.put("/localcss/**","anon");
        filterMap.put("/localjs/**","anon");

        filterMap.put("/dologin","anon");
        filterMap.put("/logout","logout");

        //静态演示
      /*  filterMap.put("/user/list","perms[用户列表]");
        filterMap.put("/user/add","perms[用户添加]");
//        filterMap.put("/user/edit","perms[用户编辑]");
        filterMap.put("/user/delete","perms[用户删除]");*/
        //动态演示
        List<Right> rights = this.findAllRights();
        for (Right right : rights) {
            if(right.getRightUrl()!=null&&
                    !right.getRightUrl().trim().equals("")){
                filterMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }

        filterMap.put("/**","authc");

        return filterMap;

    }
    @Override
    public void reloadFilterChainDefinitions() {
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext=request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter=(AbstractShiroFilter) WebApplicationContextUtils
                    .getRequiredWebApplicationContext(servletContext)
                    .getBean("shiroFilterFacotry");
            synchronized (shiroFilter){
                //获取过滤管理器
                PathMatchingFilterChainResolver filterChainResolver=
                        (PathMatchingFilterChainResolver)shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager=(DefaultFilterChainManager)filterChainResolver
                        .getFilterChainManager();
                //清空初始配置
                manager.getFilterChains().clear();
                //重新加载动态权限，配置验证规则
                Map<String,String> chains=loadFilterChainDefinitions();
                for (Map.Entry<String,String> entry:chains.entrySet()
                ) {
                    String url=entry.getKey();
                    String chainDefinition=entry.getValue().trim().replace(" ","");
                    manager.createChain(url,chainDefinition);
                }
                System.out.println("更新权限成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public IPage<Right> getRightsByPage(String rightText,String rightType,
                                        Integer pageNo, Integer pageSize) {
        //组装分页条件
        Page<Right> page=new Page<>(pageNo,pageSize);

        //组装过滤条件
        Map<String,Object> param=new HashMap<>();
        param.put("rightText",rightText);
        param.put("rightType",rightType);

        //调用分页方法
        IPage<Right> rolePage=rightMapper.getRightsByPage(page, param);

        //返回分页对象
        return rolePage;
    }

    @Override
    public void addRight(Right right) {
        rightMapper.insert(right);
    }

    @Override
    public Right getRight(String rightCode) {
        return rightMapper.selectById(rightCode);
    }

    @Override
    public void updateRight(Right right) {
        rightMapper.updateById(right);
    }

    @Override
    public void deleteRight(String rightCode) {
        rightMapper.deleteById(rightCode);
    }

    @Override
    public List<Right> findRightsByRightType(String rightType) {
        QueryWrapper<Right> qw=new QueryWrapper();
        qw.eq("right_type",rightType);
        return rightMapper.selectList(qw);
    }
}
